package com.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {
    //定义一个properties对象用来加载配置文件
    private static Properties properties = new Properties();
    //随着类的加载而加载,静态代码块
    static {
        //1、注册驱动
        try {
            //获取输入流   通过类加载器获取指定文件的输入流
            InputStream resourceAsStream =
                    JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //将配置文件进行加载 ,加载完成之后{key:value,key:value}
            properties.load(resourceAsStream);
            //根据key获取value
            String driverClassName = properties.getProperty("driverClassName");
            Class.forName(driverClassName); //加载Driver类
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection(){
        Connection connection = null;
        //如果连接的是本机，端口号也是3306  localhost：3306可以省略
        try {
            String url = properties.getProperty("jdbcUrl");
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");
//            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myclass", "root", "123");
            connection =
                    DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //释放资源
    public  static void release(ResultSet resultSet, Statement statement, Connection connection){
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }


    //开启事务
    public static void begin(Connection connection){
        try {
            connection.setAutoCommit(false);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //提交事务
    public static void commit(Connection connection){
        try {
            connection.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //回滚事务
    public static void rollback(Connection connection){
        try {
            connection.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
